package drds.data_propagate.parse.table_meta_data.dao;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Statement;


public class MetaDataBaseDao extends SqlMapClientDaoSupport {

    protected void initTable(String tableName) throws Exception {
        Connection connection = null;
        InputStream inputStream = null;
        try {
            DataSource dataSource = getDataSource();
            connection = dataSource.getConnection();
            String name = "mysql";
            inputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("ddl/" + name + "/" + tableName + ".sql");
            if (inputStream == null) {
                return;
            }

            String sql = StringUtils.join(IOUtils.readLines(inputStream), "\n");
            Statement statement = connection.createStatement();
            statement.execute(sql);
            statement.close();
        } catch (Throwable e) {
            logger.warn("init " + tableName + " failed", e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (connection != null) {
                connection.close();
            }
        }
    }


}
